import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)
const Tabbar = () => import('@/components/app-tabbar.vue')
const Home = () => import('@/views/home')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const User = () => import('@/views/user')
const Artcile = () => import('@/views/article')
const Login = () => import('@/views/login')
const UserProfile = () => import('@/views/user/profile')
const Chat = () => import('@/views/user/chat.vue')

const routes = [

  {
    path: '/',
    components: { default: Home, tabbar: Tabbar }
  },

  {
    path: '/video',
    components: { default: Video, tabbar: Tabbar }
  },

  {
    path: '/question',
    components: { default: Question, tabbar: Tabbar }
  },
  {
    path: '/user',
    components: { default: User, tabbar: Tabbar }
  },
  { path: '/article', component: Artcile },
  { path: '/login', component: Login },
  { path: '/user/profile', component: UserProfile },
  { path: '/user/chat', component: Chat }

]

const router = new VueRouter({
  routes
})

// 重写VueRouter原型对象上的push方法, 覆盖原来抛出异常的方法, "吞掉"异常
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, resolve, reject) {
  if (resolve || reject) return originalPush.call(this, location, resolve, reject)
  return originalPush.call(this, location).catch((e) => {})
}

// 导航守卫
// 约定好将来用户相关的页面 路由地址以 /user 开头
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // 没登录却访问user下的路由
  if (!token && to.path.startsWith('/user')) {
    return next('/login?returnUrl=' + encodeURIComponent(to.fullPath))
  }
  // 其他情况放行
  next()
})

export default router
